package com.xxxx.springboot.shiro;

import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xxxx.springboot.shiro.config.ResultVO;

@RequestMapping("/admin")
@Controller
public class SessionController {
	@Autowired
	private SessionDAO sessionDAO;

	/**
	 * 在线session
	 * 
	 * @return
	 */
	@GetMapping("/sessions")
	@ResponseBody
	public ResultVO<String> list() {
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		sessions.stream().forEach(a -> {
			System.out.println("用户名："
					+ a.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY"));
			System.out.println("用户session ID：" + a.getId());
			System.out.println("用户ip：" + a.getHost());
		});
		return ResultVO.success(sessions.size() + "");
	}

	/**
	 * 强制下线某个session
	 * 
	 * @return
	 */
	@GetMapping("/sessions/{sessionId}/forceLogout")
	@ResponseBody
	public ResultVO<String> forceLogout(@PathVariable("sessionId") String sessionId,
			RedirectAttributes redirectAttributes) {
		try {
			Session session = sessionDAO.readSession(sessionId);

			if (session != null) {
				session.stop();
			}
		} catch (Exception e) {
			/* ignore */}
		return ResultVO.success("强制退出成功！");
	}
}
